package org.opens.javaskill.useJsScript;

import org.junit.Test;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class UseJsDemo1 {

    @Test
    public void test1() throws ScriptException, NoSuchMethodException {
        // 获取JS执行引擎
        ScriptEngine se = new ScriptEngineManager().getEngineByName("javascript");
        se.eval("function sum(x1, x2) {return x1 + x2;}");
        if (se instanceof Invocable) {
            Invocable in = (Invocable) se;
            int a = 123;
            int b = 456;
            Double result = (Double) in.invokeFunction("sum", a, b);
            System.out.println("获得的结果：" + result);
        }
    }

    @Test
    public void test2() throws ScriptException, NoSuchMethodException {
        // 获取JS执行引擎
        ScriptEngine se = new ScriptEngineManager().getEngineByName("javascript");
        se.eval("function sum(x1, x2) {return x1 + x2;}");
        if (se instanceof Invocable) {
            Invocable in = (Invocable) se;
            int a = 123;
            int b = 456;
            String result =  in.invokeFunction("sum", a, b).toString();
            System.out.println("获得的结果：" + result);
        }
    }

}
